package com.uu.husky.Freemaker;

import com.uu.husky.entity.Student;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.URL;
import java.util.*;

/**
 * 描述：
 *
 * @author liupenghao
 * @create 2018-04-13 21:06
 **/
public class Test1 {

    /**
     * freemarker 替换工具类
     *
     * @param needReplaceMapData 需要替换数据的map 集合
     * @param templateFilePath   魔板文件路径
     * @param templateFileName   魔板文件名称
     * @param writer             输出流
     */
    public static void freemarkerProcess(Map needReplaceMapData, String templateFilePath, String templateFileName, Writer writer) {

        Configuration cfg = new Configuration();
        //  cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        cfg.setClassicCompatible(true);
        try {
            TemplateLoader templateLoader = new FileTemplateLoader(new File(
                    templateFilePath));
            cfg.setTemplateLoader(templateLoader);
            Template template = cfg.getTemplate(templateFileName);


            template.process(needReplaceMapData, writer);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }

    // test
    public static void main(String[] args) throws IOException {
        URL url = Thread.currentThread().getContextClassLoader().getResource("");
        HashMap<String, Object> needReplaceMapData = new HashMap<String, Object>();
        /******************************************单个属性************************************/
        needReplaceMapData.put("name", "刘亦菲");


        /******************************************list 属性添加***********************************/
        List<Student> students = new ArrayList<Student>();
        for (int i = 0; i < 2; i++) {
            Student student = new Student();
            student.setId(i);
            student.setName(" 葫芦娃" + i + "号");
            students.add(student);
        }
        needReplaceMapData.put("students", students);

        /******************************************日期 ***********************************/
        needReplaceMapData.put("date", new Date());

        needReplaceMapData.put("showDate", true);

        needReplaceMapData.put("imgUrl", "http://n.sinaimg.cn/translate/344/w700h1244/20180410/B_F_-fyzeyqa1740187.jpg");

        needReplaceMapData.put("description", "描述                        一只猫");

        freemarkerProcess(needReplaceMapData, url.getPath(), "template.ftl",
                new FileWriter(new File("result.html"))
        );

     //   Html2Pdf.html2pdf("result.html","result.pdf");

    }
}
